package com.hejie.videoservice.controller;

import com.hejie.common.domain.PageResult;
import com.hejie.common.domain.ResponseResult;
import com.hejie.videoservice.dto.VideoDTO;
import com.hejie.videoservice.dto.VideoPageQueryDTO;
import com.hejie.videoservice.dto.VideoUploadRequest;
import com.hejie.videoservice.entity.Video;
import com.hejie.videoservice.service.VideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/videos")
@Api(tags = "视频管理接口")
public class VideoController {

    @Resource
    private VideoService videoService;

    @PostMapping
    @ApiOperation("上传视频")
    public ResponseResult<VideoDTO> uploadVideo(@ModelAttribute VideoUploadRequest uploadRequest, Authentication authentication) {
        // 获取当前登录用户ID
        Long userId = Long.valueOf(authentication.getName());
        uploadRequest.setUserId(userId);
        VideoDTO videoDTO = videoService.uploadVideo(uploadRequest);
        return ResponseResult.success(videoDTO);
    }

    @GetMapping("/{id}")
    @ApiOperation("获取视频详情")
    public ResponseResult<VideoDTO> getVideoById(@PathVariable Long id) {
        VideoDTO videoDTO = videoService.getVideoById(id);
        return ResponseResult.success(videoDTO);
    }

    @PutMapping("/{id}")
    @ApiOperation("更新视频信息")
    public ResponseResult<VideoDTO> updateVideo(@PathVariable Long id, @RequestBody Map<String, Object> updateFields, Authentication authentication) {
        // 获取当前登录用户ID
        Long userId = Long.valueOf(authentication.getName());
        updateFields.put("currentUserId", userId);
        VideoDTO videoDTO = videoService.updateVideo(id, updateFields);
        return ResponseResult.success(videoDTO);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除视频")
    public ResponseResult<Boolean> deleteVideo(@PathVariable Long id, Authentication authentication) {
        // 获取当前登录用户ID并验证权限（实际实现应在service层）
        boolean result = videoService.deleteVideo(id);
        return ResponseResult.success(result);
    }

    @GetMapping("/user/{userId}")
    @ApiOperation("查询用户视频")
    public ResponseResult<PageResult<VideoDTO>> getUserVideos(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size, Sort.by("createTime").descending());
        Page<VideoDTO> videoPage = videoService.getUserVideos(userId, pageable);
        return ResponseResult.success(new PageResult<>(videoPage.getTotalElements(), videoPage.getContent()));
    }

    @GetMapping("/category/{categoryId}")
    @ApiOperation("查询分类视频")
    public ResponseResult<PageResult<VideoDTO>> getCategoryVideos(
            @PathVariable Long categoryId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size, Sort.by("createTime").descending());
        Page<VideoDTO> videoPage = videoService.getCategoryVideos(categoryId, pageable);
        return ResponseResult.success(new PageResult<>(videoPage.getTotalElements(), videoPage.getContent()));
    }

    @GetMapping("/search")
    @ApiOperation("搜索视频")
    public ResponseResult<PageResult<VideoDTO>> searchVideos(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size);
        Page<VideoDTO> videoPage = videoService.searchVideos(keyword, pageable);
        return ResponseResult.success(new PageResult<>(videoPage.getTotalElements(), videoPage.getContent()));
    }

    @GetMapping("/hot")
    @ApiOperation("获取热门视频")
    public ResponseResult<PageResult<VideoDTO>> getHotVideos(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size);
        Page<VideoDTO> videoPage = videoService.getHotVideos(pageable);
        return ResponseResult.success(new PageResult<>(videoPage.getTotalElements(), videoPage.getContent()));
    }

    @GetMapping("/latest")
    @ApiOperation("获取最新视频")
    public ResponseResult<PageResult<VideoDTO>> getLatestVideos(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size, Sort.by("createTime").descending());
        Page<VideoDTO> videoPage = videoService.getLatestVideos(pageable);
        return ResponseResult.success(new PageResult<>(videoPage.getTotalElements(), videoPage.getContent()));
    }

    @PostMapping("/batch")
    @ApiOperation("批量获取视频")
    public ResponseResult<List<VideoDTO>> batchGetVideos(@RequestBody List<Long> ids) {
        List<VideoDTO> videoDTOs = videoService.batchGetVideos(ids);
        return ResponseResult.success(videoDTOs);
    }

    @PutMapping("/{id}/status")
    @ApiOperation("更新视频状态")
    public ResponseResult<VideoDTO> updateVideoStatus(
            @PathVariable Long id,
            @RequestParam Video.VideoStatus status) {
        VideoDTO videoDTO = videoService.updateVideoStatus(id, status);
        return ResponseResult.success(videoDTO);
    }

    @PostMapping("/{id}/view")
    @ApiOperation("增加视频观看次数")
    public ResponseResult<Boolean> incrementViewCount(@PathVariable Long id) {
        boolean result = videoService.incrementViewCount(id);
        return ResponseResult.success(result);
    }

    @GetMapping
    @ApiOperation("分页查询视频")
    public ResponseResult<PageResult<VideoDTO>> queryVideos(VideoPageQueryDTO queryDTO,
                                                             @RequestParam(defaultValue = "0") int page,
                                                             @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<VideoDTO> videoPage = videoService.queryVideos(queryDTO, pageable);
        return ResponseResult.success(new PageResult<>(videoPage.getTotalElements(), videoPage.getContent()));
    }
}